package com.phone.servlet;

import com.phone.DBHelper;
import com.phone.entity.Result;
import com.phone.entity.ServiceControl;
import com.phone.entity.ServiceRecord;
import com.phone.entity.User;
import com.phone.exception.BaseException;
import com.phone.handle.ControlHandle;
import com.phone.handle.ServiceHandle;
import com.phone.handle.UserHandle;
import com.phone.json.JsonService;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.json.JSONObject;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.reflect.Modifier;
import java.util.Date;

/**
 * Created by tisen on 2017/8/22.
 */
@WebServlet(name = "Service", urlPatterns = "/service")
public class PublicService extends BaseServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("UTF-8");
        setParamterRequest(request);
        Session session = DBHelper.getSession();
        session.beginTransaction();
        JsonService service = new JsonService();
        service.setResult(ERROR);
        try {

            String model = getParamterString("model", false);
            String serial = getParamterString("serial", true, "default");
            boolean status = getParamterBoolean("status", true, false);

            ServiceControl serviceControl = session.get(ServiceControl.class, model);
            if (serviceControl == null) {
                status = false;
                serviceControl = new ServiceControl(model, status);
                session.save(serviceControl);
            }
            session.saveOrUpdate(new ServiceRecord(serial, serviceControl, status));
            status = serviceControl.isStatus();
            service = new JsonService(SUCCESS, "get status success", model, status);
            System.out.println(service.toString());
            session.getTransaction().commit();
        } catch (HibernateException exception) {
            exception.printStackTrace();
            session.getTransaction().rollback();
        } catch (BaseException exception) {
            exception.printStackTrace();
            session.getTransaction().rollback();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (session != null && session.isOpen())
                session.close();
            out(response, new JSONObject(service).toString());
        }
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request, response);
    }
}
